<template>
  <div class="app">
    <el-row>
      <!-- 上传按钮 -->
      <el-col :span="24" style="margin-bottom: 20px;">
        <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
            accept="image/*"
            :http-request="customHttpRequest"
        >
          <!--          <el-button type="primary" icon="el-icon-upload2">上传文件</el-button>-->
        </el-upload>
        <el-col :span="24" style="margin-bottom: 20px;">
          <el-button type="primary" @click="openDialog">上传图片</el-button>
        </el-col>
      </el-col>

      <!-- 文件列表 -->
      <el-col :span="24">
        <el-table :data="fileList" border>
          <el-table-column label="文件名" prop="name" />
          <el-table-column label="文件路径" prop="path" />
          <el-table-column label="描述" prop="link" />
          <el-table-column label="类型">
            <template #default="{ row }">
              <span>
                <!-- 根据数字返回对应的类型 -->
                {{ getTypeName(row.type) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="时间" prop="time" />

          <!-- 新增图片列 -->
          <el-table-column label="预览">
            <template #default="{ row }">
              <!-- 这里假设 row.path 是图片的 URL -->
              <img :src="row.url" alt="图片预览" style="width: 100%; height: 100px; object-fit: cover;" />
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="danger" @click="deleteFile(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <!-- AddUser 弹窗组件 -->
      <AddBannerResource
          :addDialogVisible="addDialogVisible"
          @closeDialog="addDialogVisible = false"
          @addSuccess="handleAddSuccess"
      />
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElUpload, ElRow, ElCol, ElMessage } from 'element-plus';
import AddUser from '@/views/user/AddUser.vue';
import AddBannerResource from "@/views/resource/AddBannerResource.vue";
import { getFileListApi, uploadFileApi, deleteFileApi } from '@/api/bannerResApi'; // 引入API

export default {
  components: {
    ElButton,
    ElTable,
    ElTableColumn,
    ElUpload,
    ElRow,
    ElCol,
    AddUser,
    AddBannerResource
  },
  setup() {
    const fileList = ref([]);
    const uploadUrl = '/indexRes/upload';  // 定义上传文件的URL（可以根据需要动态调整）
    const getTypeName = (type) => {
      const typeMap = {
        1: '推荐图',
        2: '直播专区',
        3: '活动专区',
        4: '最近上新',

      };
      return typeMap[type] || '未知类型'; // 默认返回 '未知类型'
    }
    // 控制弹窗显示的状态
    const addDialogVisible = ref(false);

    // 打开弹窗
    const openDialog = () => {
      addDialogVisible.value = true;
    };

    // 处理添加成功的逻辑
    const handleAddSuccess = () => {
      // 你可以在这里添加你需要的逻辑，例如刷新列表等
      console.log('用户添加成功');
      addDialogVisible.value = false; // 关闭弹窗
      getFileList();  // 刷新文件列表

    };

    // 获取文件列表
    const getFileList = async () => {
      try {
        const response = await getFileListApi();
        fileList.value = response.data || [];
        console.log(fileList.value)
      } catch (error) {
        console.error('Failed to fetch file list:', error);
        ElMessage.error('获取文件列表失败');
      }
    };

    // 删除文件
    const deleteFile = async (fileId) => {
      try {
        const response = await deleteFileApi(fileId);
        if (response.success) {
          ElMessage.success('文件删除成功');
          getFileList();  // 刷新文件列表
        } else {
          ElMessage.error('文件删除失败');
        }
      } catch (error) {
        console.error('Failed to delete file:', error);
        ElMessage.error('删除文件失败');
      }
    };

    // 上传成功回调
    const handleUploadSuccess = (response, file, fileList) => {
      ElMessage.success('文件上传成功');
      getFileList();  // 刷新文件列表
    };

    // 上传失败回调
    const handleUploadError = (error, file, fileList) => {
      ElMessage.error('文件上传失败');
    };

    // 自定义请求方法，用于上传
    const customHttpRequest = async (options) => {
      const formData = new FormData();
      formData.append('file', options.file);
      try {
        const response = await uploadFileApi(formData);
        options.onSuccess(response.data, options.file);  // 返回上传成功的数据
      } catch (error) {
        options.onError(error);  // 上传失败回调
      }
    };

    // 页面加载时获取文件列表
    onMounted(() => {
      getFileList();
    });

    return {
      fileList,
      getTypeName,
      uploadUrl,
      getFileList,
      deleteFile,
      handleUploadSuccess,
      handleUploadError,
      customHttpRequest,
      addDialogVisible,
      openDialog,
      handleAddSuccess
    };
  }
};
</script>

<style scoped>
.upload-demo i {
  margin-right: 10px;
}
</style>